<template>
  <div class="map-container">
    <div class="mapCheckedBox">
      <el-checkbox v-model="areaChecked" class="white-text-checkbox"
        >显示情报区域范围</el-checkbox
      >
    </div>
    <div ref="chartRef" class="chart-container"></div>

    <div class="mapTabs">
      <div
        class="tab"
        style="margin-left: -10px"
        @click="handleDetail('0')"
        :class="{ tabCur: currTabIndex == '0' }"
      >
        机场预测详情
      </div>
      <div
        class="tab tabs"
        @click="handleDetail('1')"
        :class="{ tabCur: currTabIndex == '1' }"
      >
        机场终端区预测详情
      </div>
      <div
        @click="handleDetail('2')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '2' }"
      >
        区域统计预测详情
      </div>
      <div
        @click="handleDetail('3')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '3' }"
      >
        航路态势预测详情
      </div>
      <div
        @click="handleDetail('4')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '4' }"
      >
        航路分时预测详情
      </div>
      <div
        @click="handleDetail('5')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '5' }"
      >
        航线分时预测详情
      </div>
    </div>
    <DetailAir
      v-if="currTabIndex == '0'"
      :airTestsObj="airTestsObj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailAir
      v-if="currTabIndex == '0Spa'"
      :airTestsObj="airTestsObjSpa"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailAir
      v-if="currTabIndex == '1'"
      :airTestsObj="airTests1Obj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailAir
      v-if="currTabIndex == '1Spa'"
      :airTestsObj="airTestsObj1Spa"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailArea
      v-if="currTabIndex == '2'"
      :airTestsAreaObj="airTestsAreaObj"
      @update-curr-detail-index="handleTabChange"
    />

    <DetailArea
      v-if="currTabIndex == '2Spa'"
      :airTestsAreaObj="airTestsArea2Obj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailRoute
      v-if="currTabIndex == '3'"
      :airTestsRouteObj="airTestsRouteObj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailFilter
      v-if="currTabIndex == '4' || currTabIndex == '5'"
      :airTestsFilterObj="airTestsFilterObj"
      @update-curr-detail-index="handleTabChange"
    />
    <NoDatas
      v-if="currTabIndex == '6'"
      @update-curr-detail-index="handleTabChange"
    />
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  watch,
  nextTick,
  computed,
  defineProps,
} from "vue";
import * as echarts from "echarts/core";
import { GeoComponent, TooltipComponent } from "echarts/components";
import { MapChart, LinesChart, ScatterChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import isValidValue from "@/utils/tools/isValidValue";
import DetailAir from "./detailAir.vue";
import DetailArea from "./detailArea.vue";
import DetailRoute from "./detailRoute.vue";
import DetailFilter from "./detailFilter.vue";
import NoDatas from "./noDatas.vue";
import { firApi } from "@/api/tabOne";

// 注册所需模块
echarts.use([
  GeoComponent,
  MapChart,
  ScatterChart,
  LinesChart,
  CanvasRenderer,
  TooltipComponent,
]);

// 接收父组件传递的机场数据
const props = defineProps({
  airports: {
    type: Array,
    default: () => [],
  },
  airports1: {
    type: Array,
    default: () => [],
  },
  airports2: {
    type: Array,
    default: () => [],
  },
  areaStatic: {
    type: Array,
    default: () => [],
  },
  areaStatic1: {
    type: Array,
    default: () => [],
  },
  routeWayPoints: {
    type: Array,
    default: () => [],
  },
  airTestsObj: {
    type: Object,
    default: () => ({}),
  },
  airTests1Obj: {
    type: Object,
    default: () => ({}),
  },
  airTestsAreaObj: {
    type: Array,
    default: () => [],
  },
  airTestsRouteObj: {
    type: Array,
    default: () => [],
  },
  airTestsFilterObj: {
    type: Array,
    default: () => [],
  },
});

const currTabIndex = ref("");
const airTestsObjSpa = ref({}); // 单个机场详情
const airTestsObj1Spa = ref({}); // 单个机场终端详情
const airTestsArea2Obj = ref([]); // 单个区域终端详情

// 组件状态
const areaChecked = ref(false);
const chartRef = ref(null);
const chart = ref(null);
const isReady = ref(false);
const lineWidth = computed(() => 1);
const gridLines = ref([]);
const gridSize = ref(2.5);
const visibleRange = ref({
  minLon: 0,
  maxLon: 0,
  minLat: 0,
  maxLat: 0,
});
const isFirstLoad = ref(true);
const pathData = ref([]); // 存储请求返回的路径数据
const pathSeriesName = "simulatePath"; // 路径系列的唯一名称（用于定位和删除）

const legendConfig = computed(() => {
  // 情况1：显示 areaStatic 的图例（2个元素：红色矩形 + “不可用”文本）
  if (isValidValue(props.areaStatic)) {
    return [
      {
        type: "rect",
        right: 60,
        top: 20,
        zlevel: 5,
        shape: { width: 12, height: 12 },
        style: { fill: "#ff0000" },
      },
      {
        type: "text",
        right: 20,
        top: 20,
        zlevel: 5,
        style: { text: "不可用", fontSize: 12, fill: "#ffffff" },
      },
    ];
  }
  // 情况2：显示 areaStatic1 的图例（18个元素：9个彩色矩形 + 9个文本）
  else if (isValidValue(props.areaStatic1)) {
    const legendItems = [
      { color: "#7cfa8d", text: "0", top: 20 },
      { color: "#4dad51", text: "1-5", top: 45 },
      { color: "#2f7132", text: "6-10", top: 70 },
      { color: "#d7fc62", text: "11-20", top: 95 },
      { color: "#fcfe54", text: "21-30", top: 120 },
      { color: "#f8cf59", text: "31-40", top: 145 },
      { color: "#f19135", text: "41-50", top: 170 },
      { color: "#ee692c", text: "51-60", top: 195 },
      { color: "#ec3323", text: ">60", top: 220 },
    ];
    let legendArr = [];
    legendItems.forEach((item) => {
      legendArr.push({
        type: "rect",
        right: 60,
        top: item.top,
        zlevel: 5,
        shape: { width: 12, height: 12 },
        style: { fill: item.color },
      });
      legendArr.push({
        type: "text",
        right: 20,
        top: item.top,
        zlevel: 5,
        style: { text: item.text, fontSize: 12, fill: "#ffffff" },
      });
    });
    return legendArr;
  }
  // 情况3：两者都不存在，返回空数组（彻底清除所有图例）
  else {
    return [];
  }
});

const handleTabChange = (newTabIndex) => {
  currTabIndex.value = newTabIndex;
};

// 地图常量配置
const MAP_CONFIG = {
  backgroundColor: "transparent",
};

// 异步加载地图数据
const loadMapData = async () => {
  try {
    const { default: chinaJson } = await import("@/assets/china.json");
    echarts.registerMap("china", chinaJson);
    return true;
  } catch (error) {
    console.error("地图数据加载失败:", error);
    return false;
  }
};

const getFir = async () => {
  const { code, data } = await firApi();
  if (code === 200) {
    return data;
  }
};

const handleDetail = (index) => {
  if (index == 0 && isValidValue(props.airTestsObj.airportResults)) {
    currTabIndex.value = index;
  } else if (index == 1 && isValidValue(props.airTests1Obj)) {
    currTabIndex.value = index;
  } else if (index == 2 && isValidValue(props.airTestsAreaObj)) {
    currTabIndex.value = index;
  } else if (index == 3 && isValidValue(props.airTestsRouteObj)) {
    currTabIndex.value = index;
  } else {
    currTabIndex.value = "6";
  }
};

// 绘制网格 - 只在首次加载时执行
const drawGrid = () => {
  if (!isReady.value || !isFirstLoad.value) return;

  gridLines.value = generateGridData();
  const option = chart.value.getOption();
  const nonGridSeries = option.series.filter(
    (series) => series.type === "map" || series.type === "scatter"
  );

  chart.value.setOption({
    series: [...nonGridSeries, ...gridLines.value],
  });
};

const generateGridData = () => {
  const lines = [];
  const { minLon, maxLon, minLat, maxLat } = visibleRange.value;
  const step = gridSize.value;

  const startLat = Math.ceil(minLat / step) * step;
  const endLat = Math.floor(maxLat / step) * step;

  for (let lat = startLat; lat <= endLat; lat += step) {
    const fixedLat = Number(lat.toFixed(1));
    lines.push({
      tip: "绘制网格线",
      type: "lines",
      zlevel: 3,
      name: `纬线_${fixedLat}`,
      coordinateSystem: "geo",
      polyline: true,
      lineStyle: {
        width: lineWidth.value,
        color: "rgba(0,59,122,1)",
        type: "solid",
      },
      // 新增：禁用tooltip和高亮
      tooltip: { show: false },
      emphasis: { disabled: true },
      // emphasis: {
      //   disabled: false,
      // },
      data: [
        [
          [minLon, fixedLat],
          [maxLon, fixedLat],
        ],
      ],
    });
  }

  const startLon = Math.ceil(minLon / step) * step;
  const endLon = Math.floor(maxLon / step) * step;

  for (let lon = startLon; lon <= endLon; lon += step) {
    const fixedLon = Number(lon.toFixed(1));
    lines.push({
      type: "lines",
      name: `经线_${fixedLon}`,
      zlevel: 3,
      coordinateSystem: "geo",
      polyline: true,
      lineStyle: {
        width: lineWidth.value,
        color: "rgba(0,59,122,1)",
        type: "solid",
      },
      tooltip: { show: false },
      emphasis: { disabled: true },
      // emphasis: {
      //   disabled: false, // 开启，否则无法触发 tooltip
      // },
      data: [
        [
          [fixedLon, minLat],
          [fixedLon, maxLat],
        ],
      ],
    });
  }

  return lines;
};

// 初始化图表 - 只在首次加载时执行
const initChart = () => {
  if (!isReady.value || !chart.value || !isFirstLoad.value) return;

  const option = {
    backgroundColor: MAP_CONFIG.backgroundColor,
    graphic: legendConfig.value,
    tooltip: {
      show: true,
      trigger: "item",
      //   formatter: (params) => {
      //     if (params.seriesType === "lines") {
      //       const name = params.seriesName;
      //       if (name.startsWith("纬线_")) {
      //         const lat = name.split("_")[1];
      //         return `纬线: ${lat}°N`;
      //       }
      //       // 匹配经线（格式：经线_102.5）
      //       else if (name.startsWith("经线_")) {
      //         const lon = name.split("_")[1];
      //         return `经线: ${lon}°E`;
      //       }
      //       return "网格线信息";
      //     }

      //     if (!params.value || !Array.isArray(params.value)) {
      //       return "经纬度信息";
      //     }
      //     const lon = Number(params.value[0]);
      //     const lat = Number(params.value[1]);
      //     if (isNaN(lon) || isNaN(lat)) {
      //       return "经纬度信息";
      //     }
      //     return `经度: ${lon.toFixed(4)}°<br>纬度: ${lat.toFixed(4)}°`;
      //   },
    },
    geo: {
      map: "china",
      // aspectScale: 0.75,
      // layoutCenter: [450, 337.5], //["50%", "52%"],
      // layoutSize: "90%",
      center: [104, 31], // 中国几何中心经纬度（可自定义）
      zoom: 1.2, // 缩放级别（1 为默认，越大地图越近）
      roam: false,
      emphasis: {
        disabled: true,
      },
      itemStyle: {
        normal: {
          borderColor: "#4896a4",
          borderWidth: 0.5,
          color: {
            type: "linear-gradient",
            x: 0,
            y: 1500,
            x2: 2500,
            y2: 0,
            colorStops: [
              { offset: 0, color: "#132c5f" },
              { offset: 1, color: "#132c5f" },
            ],
            global: true,
          },
          opacity: 0.5,
        },
        emphasis: {
          areaColor: "rgba(0, 157, 161, 0.5)",
          borderColor: "rgba(147, 235, 248, 1)",
        },
      },
      regions: [
        {
          name: "南海诸岛",
          itemStyle: {
            areaColor: "rgba(0, 10, 52, 1)",
            borderColor: "rgba(0, 10, 52, 1)",
          },
          emphasis: {
            areaColor: "rgba(0, 10, 52, 1)",
            borderColor: "rgba(0, 10, 52, 1)",
          },
        },
      ],
      z: 1,
    },
    series: [
      {
        type: "map",
        map: "china",
        tooltip: { show: false },
        label: {
          show: false,
        },

        center: [104, 30.8],
        zoom: 1.2,
        roam: false,
        emphasis: {
          disabled: true,
        },
        itemStyle: {
          normal: {
            borderColor: "rgba(147, 235, 248, 0.6)",
            borderWidth: 0.8,
            areaColor: {
              type: "linear-gradient",
              x: 0,
              y: 1200,
              x2: 1000,
              y2: 0,
              colorStops: [
                { offset: 0, color: "#132c5f" },
                { offset: 1, color: "#132c5f" },
              ],
              global: true,
            },
          },
          emphasis: {
            areaColor: "rgba(0, 157, 161, 0.5)",
            borderColor: "rgba(147, 235, 248, 0.6)",
          },
        },
        zlevel: 0,
      },
    ],
  };

  chart.value.setOption(option);

  nextTick(async () => {
    await new Promise((resolve) => setTimeout(resolve, 100));

    const container = chartRef.value;
    const { width: containerWidth, height: containerHeight } =
      container.getBoundingClientRect();

    const topLeft = chart.value.convertFromPixel("geo", [0, 0]);
    const topRight = chart.value.convertFromPixel("geo", [containerWidth, 0]);
    const bottomLeft = chart.value.convertFromPixel("geo", [
      0,
      containerHeight,
    ]);
    const bottomRight = chart.value.convertFromPixel("geo", [
      containerWidth,
      containerHeight,
    ]);

    const actualMinLon = Math.min(
      topLeft[0],
      topRight[0],
      bottomLeft[0],
      bottomRight[0]
    );
    const actualMaxLon = Math.max(
      topLeft[0],
      topRight[0],
      bottomLeft[0],
      bottomRight[0]
    );
    const actualMinLat = Math.min(
      topLeft[1],
      topRight[1],
      bottomLeft[1],
      bottomRight[1]
    );
    const actualMaxLat = Math.max(
      topLeft[1],
      topRight[1],
      bottomLeft[1],
      bottomRight[1]
    );

    visibleRange.value = {
      minLon: actualMinLon,
      maxLon: actualMaxLon,
      minLat: actualMinLat,
      maxLat: actualMaxLat,
    };

    drawGrid();
    // 首次加载时绘制机场
    updateAirports();
    // 标记为非首次加载
    isFirstLoad.value = false;

    // 绑定双击事件（核心新增）
    bindAirportDoubleClick();
  });
};

const getFilteredData = (targetKey) => {
  const newData = JSON.parse(JSON.stringify(props.airTestsObj));
  const originalResults = newData.airportResults || {};
  const filteredResults = {};

  if (Object.prototype.hasOwnProperty.call(originalResults, targetKey)) {
    filteredResults[targetKey] = originalResults[targetKey];
  } else {
    console.log(`未找到key为${targetKey}的机场数据`);
  }

  newData.airportResults = filteredResults;
  return newData;
};
const filterAirportByAirportName = (originalData, targetName) => {
  const newData = JSON.parse(JSON.stringify(originalData));
  const originalAirportResults = newData.airportResults || {};
  const filteredAirportResults = {};
  Object.keys(originalAirportResults).forEach((airportCodeKey) => {
    const currentAirportItem = originalAirportResults[airportCodeKey];
    if (currentAirportItem?.airport?.name === targetName)
      filteredAirportResults[airportCodeKey] = currentAirportItem;
  });
  newData.airportResults = filteredAirportResults;
  return newData;
};
// 根据区域的 pointId 筛选目标区域数据
const filterByAirAreaName = (originalData, targetPointId) => {
  const newData = JSON.parse(JSON.stringify(originalData));
  const filteredAreaResults = newData.filter((item) => {
    return item?.area?.pointId === targetPointId;
  });
  return filteredAreaResults;
};
// 绑定大飞机双击事件
const bindAirportDoubleClick = () => {
  if (!chart.value) return;

  chart.value.on("dblclick", (params) => {
    // 仅处理飞机系列的双击事件
    if (params.seriesName === "airports" && params.data?.isBigPlane) {
      const filterData = getFilteredData(params.data.airportCode);
      airTestsObjSpa.value = filterData;
      currTabIndex.value = "0Spa";
    }
    // 黄色飞机场双击逻辑
    if (params.seriesName === "parkingLots") {
      airTestsObj1Spa.value = filterAirportByAirportName(
        props.airTests1Obj,
        params.data.name
      );
      currTabIndex.value = "1Spa";
    }
    // 静态区域统计矩形双击逻辑
    if (params.seriesName === "areaStaticStatRect") {
      airTestsArea2Obj.value = filterByAirAreaName(
        props.airTestsAreaObj,
        params.data.area.pointId
      );
      currTabIndex.value = "2Spa";
    }
  });
};

// 更新机场数据
const updateAirports = () => {
  const greenPlane = new URL(
    "../../../assets/images/raim/airlvicon.png",
    import.meta.url
  ).href;
  const bigPlane = new URL(
    "../../../assets/images/raim/airlanbigicon.png",
    import.meta.url
  ).href;
  const planeLot = new URL(
    "../../../assets/images/raim/planelot.png",
    import.meta.url
  ).href;

  if (!isReady.value || !chart.value) return;

  const airports1NameSet = new Set(
    props.airports1.map((item) => item.name?.trim())
  );
  const airportData = props.airports.map((airport) => ({
    name: airport.name,
    value: [airport.longitude, airport.latitude],
    isBigPlane: airports1NameSet.has(airport.name?.trim()),
    ...airport,
  }));

  const smallPlaneData = airportData.filter((item) => !item.isBigPlane);
  const bigPlaneData = airportData.filter((item) => item.isBigPlane);
  const finalAirportData = [...smallPlaneData, ...bigPlaneData];

  const option = chart.value.getOption();
  const oldAirportSeriesIndex = option.series.findIndex(
    (s) => s.name === "airports"
  );
  if (oldAirportSeriesIndex !== -1) {
    option.series.splice(oldAirportSeriesIndex, 1);
  }

  option.series.push({
    type: "scatter",
    name: "airports",
    coordinateSystem: "geo",
    zlevel: 4,
    tooltip: {
      show: true,
      trigger: "item",
      padding: 12,
      backgroundColor: "rgba(0, 15, 40, 0.9)",
      borderColor: "rgba(147, 235, 248, 0.8)",
      borderWidth: 1,
      textStyle: { color: "#fff", fontSize: 13, lineHeight: 1.5 },
      formatter: (params) => {
        if (params.data?.isBigPlane) {
          return `
            <div>
              <p><b>名称：</b>(${params.data.airportCode})${params.data.city}/${params.data.name}</p>
              <p><b>经度：</b>${params.data.longitude}</p>
              <p><b>纬度：</b>${params.data.latitude}</p>
              <p><b>海拔：</b>${params.data.elevation}</p>
            </div>
          `;
        }
        return "";
      },
    },
    data: finalAirportData.map((item) => {
      return {
        ...item,
        symbol: `image://${item.isBigPlane ? bigPlane : greenPlane}`,
        symbolSize: item.isBigPlane ? [36, 60] : [18, 30],
        zlevel: item.isBigPlane ? 10 : 5,
      };
    }),
  });
  if (isValidValue(props.airports2)) {
    console.log(props.airports2, "props.airports2");
    const oldParkingIndex = option.series.findIndex(
      (s) => s.name === "parkingLots"
    );
    if (oldParkingIndex !== -1) {
      option.series.splice(oldParkingIndex, 1);
    }

    option.series.push({
      type: "scatter",
      name: "parkingLots",
      coordinateSystem: "geo",
      zlevel: 6, // 层级高于小飞机，低于大飞机（可根据需求调整）
      tooltip: {
        show: true,
        trigger: "item",
        padding: 12,
        backgroundColor: "rgba(0, 15, 40, 0.9)",
        borderColor: "rgba(147, 235, 248, 0.8)",
        borderWidth: 1,
        textStyle: { color: "#fff", fontSize: 13, lineHeight: 1.5 },
        formatter: (params) => {
          console.log(params, "机场预测悬浮对象");
          return `
          <div>
            <p><b>名称：</b>(${params.data.airportCode})${params.data.city}/${params.data.name}</p>
            <p><b>经度：</b>${params.data.longitude}</p>
            <p><b>纬度：</b>${params.data.latitude}</p>
            <p><b>海拔：</b>${params.data.elevation}</p>
          </div>
        `;
        },
      },
      data: props.airports2.map((parking) => ({
        ...parking,
        symbol: `image://${planeLot}`,
        symbolSize: [24, 40],
        zlevel: 6,
      })),
    });
  }
  if (isValidValue(props.areaStatic)) {
    const oldAreaStaticIndex = option.series.findIndex(
      (s) => s.name === "areaStaticRect"
    );
    if (oldAreaStaticIndex !== -1) {
      option.series.splice(oldAreaStaticIndex, 1);
    }

    const rectWidth = 22;
    const rectHeight = 32;
    const pixelOffsetLon = 18;
    const pixelOffsetLat = 18;
    const { width: containerWidth } = chartRef.value.getBoundingClientRect();
    const geoModel = chart.value.getModel().getComponent("geo");
    const [visMinLon, visMaxLon] = geoModel.option.longitudeRange || [73, 135];
    const lonRange = visMaxLon - visMinLon;

    const pixelToLon = lonRange / containerWidth;
    const pixelToLat = pixelToLon;

    const offsetLon = pixelOffsetLon * pixelToLon;
    const offsetLat = pixelOffsetLat * pixelToLat;

    const rectSeriesData = props.areaStatic.map((item) => {
      // 从 item.area 中提取经纬度（原代码是 item.longitude）
      const { longitude: lon, latitude: lat } = item.area;
      const gridSizeVal = gridSize.value;

      const baseAlignedLon = Math.round(lon / gridSizeVal) * gridSizeVal;
      const baseAlignedLat = Math.round(lat / gridSizeVal) * gridSizeVal;

      const alignedLon = baseAlignedLon + offsetLon;
      const alignedLat = baseAlignedLat + offsetLat;

      return {
        name: `静态区域${item.pointId}`, // 顶层对象的 pointId，无需改
        value: [alignedLon, alignedLat],
        ...item, // 展开整个 item（包含 area、startTime 等）
        alignedLon,
        alignedLat,
      };
    });

    option.series.push({
      type: "scatter",
      name: "areaStaticRect",
      coordinateSystem: "geo",
      zlevel: 4,
      symbol: "rect",
      symbolSize: [rectWidth, rectHeight],
      itemStyle: {
        color: "rgba(255,0,0,0.4)",
      },
      tooltip: {
        show: true,
        trigger: "item",
        position: (point) => {
          const tooltipWidth = 120;
          const finalX = point[0] - tooltipWidth - 10;
          const finalY = point[1];
          return [Math.max(finalX, 10), finalY];
        },
        textStyle: {
          textAlign: "left",
        },
        formatter: (params) => {
          const point = params.data;
          return `
            <div style="text-align: left !important;">
              <p style="text-align: left !important;">
                <b>经度：</b>${point.area.longitude}
              </p>
              <p style="text-align: left !important;">
                <b>纬度：</b>${point.area.latitude}
              </p>
              <p style="text-align: left !important;">
                <b>海拔：</b>${point.area.elevation}
              </p>
            </div>
          `;
        },
      },
      data: rectSeriesData,
    });
  } else {
    const oldAreaStaticIndex = option.series.findIndex(
      (s) => s.name === "areaStaticRect"
    );
    if (oldAreaStaticIndex !== -1) {
      option.series.splice(oldAreaStaticIndex, 1);
    }
  }

  if (isValidValue(props.areaStatic1)) {
    const oldAreaStaticIndex = option.series.findIndex(
      (s) => s.name === "areaStaticStatRect"
    );
    if (oldAreaStaticIndex !== -1) {
      option.series.splice(oldAreaStaticIndex, 1);
    }

    const rectWidth = 22;
    const rectHeight = 32;
    const pixelOffsetLon = 18;
    const pixelOffsetLat = 18;
    const { width: containerWidth } = chartRef.value.getBoundingClientRect();
    const geoModel = chart.value.getModel().getComponent("geo");
    const [visMinLon, visMaxLon] = geoModel.option.longitudeRange || [73, 135];
    const lonRange = visMaxLon - visMinLon;

    const pixelToLon = lonRange / containerWidth;
    const pixelToLat = pixelToLon;

    const offsetLon = pixelOffsetLon * pixelToLon;
    const offsetLat = pixelOffsetLat * pixelToLat;

    const colorLevelMap = {
      0: "#7cfa8d",
      1: "#4dad51",
      2: "#2f7132",
      3: "#d7fc62",
      4: "#fcfe54",
      5: "#f8cf59",
      6: "#f19135",
      7: "#ee692c",
      8: "#ec3323",
    };

    const rectSeriesStatData = props.areaStatic1.map((item) => {
      // 从 item.area 中提取经纬度（原代码是 item.longitude）
      const { longitude: lon, latitude: lat } = item.area;
      const gridSizeVal = gridSize.value;

      const baseAlignedLon = Math.round(lon / gridSizeVal) * gridSizeVal;
      const baseAlignedLat = Math.round(lat / gridSizeVal) * gridSizeVal;

      const alignedLon = baseAlignedLon + offsetLon;
      const alignedLat = baseAlignedLat + offsetLat;

      return {
        name: `静态区域${item.pointId}`, // 顶层对象的 pointId，无需改
        value: [alignedLon, alignedLat],
        ...item, // 展开整个 item（包含 area、startTime 等）
        alignedLon,
        alignedLat,
      };
    });

    option.series.push({
      type: "scatter",
      name: "areaStaticStatRect",
      coordinateSystem: "geo",
      zlevel: 4,
      symbol: "rect",
      symbolSize: [rectWidth, rectHeight],
      itemStyle: {
        color: (params) => {
          const level = params.data.colorLevel;
          // 若出现未定义的 level，默认返回浅灰色
          return colorLevelMap[level] || "rgba(200, 200, 200, 0.4)";
        },
        // borderColor: "#ffffff",
      },
      tooltip: {
        show: true,
        trigger: "item",
        formatter: (params) => {
          const point = params.data;
          return `
          <div>
            <p><b>经度：</b>${point.area.longitude}</p>
            <p><b>纬度：</b>${point.area.latitude}</p>
            <p><b>海拔：</b>${point.area.elevation}</p>
          </div>
        `;
        },
      },
      data: rectSeriesStatData,
    });
  } else {
    const oldAreaStaticIndex1 = option.series.findIndex(
      (s) => s.name === "areaStaticStatRect"
    );
    if (oldAreaStaticIndex1 !== -1) {
      option.series.splice(oldAreaStaticIndex1, 1);
    }
  }

  if (isValidValue(props.routeWayPoints)) {
    console.log("进入到了routeWayPoints", props.routeWayPoints);
    const pathWayPointsName = "routeWayPoints";
    // 先移除已有同名航线系列，避免重复绘制
    option.series = option.series.filter((s) => s.name !== pathWayPointsName);

    // 直接使用航点数组（无需遍历外层对象，因为props.routeWayPoints已是航点数组）
    const wayPoints = props.routeWayPoints;
    // 校验航点数量（至少2个才绘制）
    if (wayPoints.length > 1) {
      // 提取经纬度坐标
      const validCoords = wayPoints.map((point) => [
        point.longitude,
        point.latitude,
      ]);

      // 生成航线系列
      const pathSeries = {
        type: "lines",
        name: pathWayPointsName,
        zlevel: 7, // 层级高于地图和网格，确保可见
        coordinateSystem: "geo",
        polyline: true,
        lineStyle: {
          width: 1,
          color: "#72e789",
          opacity: 1.0,
          dashOffset: 5,
        },
        // tooltip: {
        //   show: true,
        //   formatter: () => `航线：`, // 若有实际航线编码可替换
        // },
        data: [
          {
            name: "航线", // 可根据实际需求修改名称
            coords: validCoords,
          },
        ],
      };

      option.series.push(pathSeries);
    } else {
      console.warn("航点数量不足2个，无法绘制航线", wayPoints);
    }
  } else {
    const pathWayPointsName = "routeWayPoints";
    option.series = option.series.filter((s) => s.name !== pathWayPointsName);
  }

  chart.value.setOption(option, {
    replaceMerge: ["series"],
    silent: false,
  });
};

const forceUpdateGraphic = () => {
  if (!chart.value || !isReady.value) return;
  const option = chart.value.getOption();

  option.graphic = legendConfig.value;

  chart.value.setOption(option, {
    silent: false,
    replaceMerge: ["graphic"],
  });
};

// 监听数据变化
watch(
  () => [
    props.airports,
    props.airports1,
    props.airports2,
    props.areaStatic,
    props.areaStatic1,
    props.routeWayPoints,
  ],
  async () => {
    forceUpdateGraphic();
    await new Promise((resolve) => setTimeout(resolve, 20));
    updateAirports();
  },
  { deep: true }
);

watch(
  areaChecked,
  async (isChecked) => {
    if (!isReady.value || !chart.value) return;

    const option = chart.value.getOption();
    if (isChecked) {
      try {
        const simulateData = await getFir();
        pathData.value = simulateData;
        option.series = option.series.filter((s) => s.name !== pathSeriesName);

        const pathSeries = simulateData
          .filter(
            (item) =>
              item?.shapePoints &&
              Array.isArray(item.shapePoints) &&
              item.shapePoints.length > 0
          )
          .map((item) => {
            const validCoords = item.shapePoints.map((point) => [
              point.longitude,
              point.latitude,
            ]);
            if (validCoords.length < 2) {
              console.warn(
                `路径${item.identifier}有效坐标不足2个，跳过绘制`,
                validCoords
              );
              return null;
            }

            // 正常生成路径系列
            return {
              type: "lines",
              name: pathSeriesName,
              zlevel: 7,
              coordinateSystem: "geo",
              polyline: true,
              lineStyle: {
                width: 1,
                color: "#00AFFF",
                opacity: 1.0,
                dashOffset: 5,
                type: "dashed",
              },
              tooltip: {
                show: true,
                formatter: () => `路径：${item.identifier || "未知区域"}`,
              },
              data: [
                {
                  name: item.identifier || "未知区域",
                  coords: validCoords, // 确保此处是经过校验的有效二维数组
                },
              ],
            };
          })
          .filter((series) => series !== null);

        option.series.push(...pathSeries);
        chart.value.setOption(option);
      } catch (error) {
        console.error("加载路径数据失败：", error);
        areaChecked.value = false;
      }
    } else {
      const option = chart.value.getOption();
      option.series = option.series.filter((s) => {
        const seriesName = s.name || "";
        return seriesName !== pathSeriesName;
      });
      chart.value.setOption(option, true);
      pathData.value = [];
    }
  },
  { immediate: false }
);

// 组件生命周期
onMounted(() => {
  const initTimer = setTimeout(() => {
    clearTimeout(initTimer);
    nextTick(async () => {
      if (!chartRef.value) return;
      chart.value = echarts.init(chartRef.value, null, {
        renderer: "canvas",
        useDirtyRect: true,
      });
      const dataLoaded = await loadMapData();
      if (!dataLoaded) {
        return;
      }
      isReady.value = true;
      initChart();
    });
  }, 100);
});

// 窗口大小监听
watch(
  () => chartRef.value?.clientWidth,
  (newWidth) => {
    if (newWidth && isReady.value) {
      chart.value.resize({ animation: { duration: 300 } });
    }
  }
);

// 组件销毁
onUnmounted(() => {
  if (chart.value) {
    chart.value.off("dblclick");
    // 销毁前移除路径系列
    const option = chart.value.getOption();
    const pathSeriesIndexes = option.series
      .map((series, index) => (series.name === pathSeriesName ? index : -1))
      .filter((index) => index !== -1);
    pathSeriesIndexes.forEach((index) => option.series.splice(index, 1));
    chart.value.setOption(option);

    chart.value.dispose();
    chart.value = null;
  }
  isReady.value = false;
  pathData.value = []; // 清空路径数据
});
</script>

<style scoped lang="scss">
.mapCheckedBox {
  position: absolute;
  left: 20px;
  z-index: 1;
  top: 7px;
  .white-text-checkbox :deep(.el-checkbox__label) {
    color: #ffffff !important;
    font-size: 12px;
  }
  // :deep(.el-checkbox__inner) {
  //   border-color: #00afff;
  //   background: transparent;
  // }
  // :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  //   background: #00afff;
  //   border-color: #00afff;
  // }
}
.mapTabs {
  width: 650px;
  height: 44px;
  margin: 0 auto;
  margin-top: 10px;
  .tab {
    cursor: pointer;
    float: left;
    margin-right: 8px;
    color: #c5d6e6;
    font-size: 12px;
    text-align: center;
    width: 100px;
    height: 44px;
    line-height: 44px;
    background-image: url("../../../assets/images/raim/tabUnChange.png");
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
  }
  .tabs {
    padding: 0 15px;
    line-height: 22px;
  }
  .tabs1 {
    padding: 0 21px;
    line-height: 22px;
  }
  .tabCur {
    color: #fff;
    background-image: url("../../../assets/images/raim/tabChange.png");
  }
}

.map-container {
  position: relative;
  margin-top: 30px;
  margin-left: 30px;
  width: calc(100% - 30px);
  // height: 675px;
  height: calc(100% - 90px);
  // float: none;
  // margin: 0;
  box-sizing: border-box;
  // overflow: hidden; // 超出父级范围的内容隐藏
  max-width: calc(100% - 30px); // 不超过父级宽度
  max-height: 100%; // 不超过父级高度
}
.chart-container {
  width: calc(100% - 30px);
  // height: 675px;
  height: 100%;
  background: transparent;
  overflow: hidden;
}

:deep(.ec-plot) {
  transition: all 0.3s ease;
}
:deep(.ec-geo) {
  .ec-geo-area {
    fill: #132c5f;
    fill-opacity: 0.5;
    stroke: #4896a4;
    stroke-width: 0.5;
  }
  .ec-geo-region[name="南海诸岛"] {
    fill: rgba(0, 10, 52, 1);
    stroke: rgba(0, 10, 52, 1);
  }
}
:deep(.ec-series-lines) {
  stroke: rgba(0, 59, 122, 1);
  stroke-width: 1;
}
:deep(.ec-series-scatter) {
  .ec-scatter-item {
    transition: transform 0.2s ease;
  }
  .ec-scatter-item:hover {
    transform: scale(1.05);
  }
}
:deep(.ec-series-lines[name="simulatePath"]) {
  stroke: #00afff;
  stroke-width: 1;
  stroke-dasharray: 5, 5;
  stroke-opacity: 1;
}
</style>
